package com.zhwmall.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhwmall.common.entity.product.CategoryBrandRelationEntity;
import com.zhwmall.common.entity.product.CategoryEntity;
import com.zhwmall.product.dao.CategoryBrandRelationDao;
import com.zhwmall.product.dao.CategoryDao;
import com.zhwmall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public List<CategoryEntity> listWithTree() {
//        1、查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);
//        2、组装成父子的树形结构
        return getParent(list);
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

        // TODO: 校验是否关联
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public void updateCategoryAndCategoryBrandRelation(CategoryEntity category) {
        baseMapper.updateById(category);

        CategoryBrandRelationEntity build = CategoryBrandRelationEntity.builder().catelogName(category.getName()).build();

        categoryBrandRelationDao.update(build, new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", category.getCatId()));
    }

    //    2.1找到所有的一级分类
    public List<CategoryEntity> getParent(List<CategoryEntity> list){
        return list.stream().filter(item->
                item.getParentCid() == 0
        ).map(item->{
            item.setChildren(getChildren(item, list));
            return item;
        }).sorted((item1, item2)->{
            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());
    }
//    2.2 递归查出所有子分类
    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        return all.stream().filter(item->
                item.getParentCid() == root.getCatId()
        ).map(item->{
            item.setChildren(getChildren(item, all));
            return item;
        }).sorted((item1, item2)->{
            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());
    }
}